package com.java;

public class ThreadAPI {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            System.out.println("线程(" + Thread.currentThread().getName() + ")开始");

            for (int i = 0; i < 5; i++) {
                System.out.println("线程(" + Thread.currentThread().getName() + ")运行中");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            System.out.println("线程(" + Thread.currentThread().getName() + ")结束");
        });

        // setName & getName：设置或获取线程名称
        System.out.println(thread.getName()); // Thread-0
        thread.setName("Thread1");
        System.out.println(thread.getName()); // Thread1

        // currentThread：获取运行当前任务线程的Thread对象
        System.out.println(Thread.currentThread().getName()); // main

        // sleep：使运行当前任务线程休眠，单位为毫秒。休眠时间到达后该线程自动醒来并等待CPU调度后继续运行
        System.out.println("休眠之前");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("休眠之后");

        // setPriority & getPriority：设置或获取线程优先级1-10，10优先级最高。理论上优先级越高抢占CPU的概率越大就越先运行，但并不是100%先运行，实际谁运行还跌看CPU调度
        System.out.println(thread.getPriority()); // 5
        thread.setPriority(10);
        System.out.println(thread.getPriority()); // 10

        // start：启动线程，同一线程启动后不能再次启动。启动线程后并不会立即运行，实际运行还跌看CPU调度，所以线程运行顺序与谁先start无关
        thread.start();
    }
}
